package com.kingdee.shr.custom.handler.buscostcount;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.workflow.WfException;
import com.kingdee.bos.workflow.service.EnactmentServiceProxy;

import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.buscostcount.BusCostCountFactory;
import com.kingdee.eas.custom.buscostcount.BusCostCountInfo;
import com.kingdee.eas.custom.buscostcount.IBusCostCount;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.DateTimeUtils;
import com.kingdee.util.StringUtils;

/**
 * 
 * Title: BusCostCountEditHandler <br>
 * Description: 班车费变动核算表单Handler -Web端
 * 
 * @author saisai_cheng Email:854296216@qq.com
 * @date 2019-8-2
 */
public class BusCostCountEditHandler extends EditHandler {
    private static Logger logger = Logger
            .getLogger("com.kingdee.eas.custom.buscostcount.handler.BusCostCountEditHandler");

    private Context ctx;

    public BusCostCountEditHandler(Context ctx) {
        this.ctx = ctx;
    }

    public BusCostCountEditHandler() {
        this.ctx = SHRContext.getInstance().getContext();
    }

    StringBuffer sql = new StringBuffer();

    /**
     * 
     * <p>
     * Title: getDeptAction
     * </p>
     * <p>
     * Description:根据员工获取其部门信息
     * </p>
     * 
     * @param request
     * @param response
     * @param model
     * @throws SHRWebException
     */
    public void getDeptAction(HttpServletRequest request, HttpServletResponse response, ModelMap model)
            throws SHRWebException {

        String personId = request.getParameter("id");// 员工id
        String orgName = null;// 组织
        String orgId = null;// 组织id
        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
        Map<String, String> dept = new HashMap<String, String>();
        IRowSet rowSet = null;

        try {
            rowSet = DbUtil.executeQuery(ctx, joinSql(personId));
            while (rowSet.next()) {
                orgName = rowSet.getString("name");
                orgId = rowSet.getString("id");
                if (!StringUtils.isEmpty(orgName) && !StringUtils.isEmpty(orgId)) {
                    dept.put("id", orgId);
                    dept.put("name", orgName);
                    map.put("dept", dept);
                }
            }
        } catch (BOSException e) {
            logger.error(e.getMessage(), e);
            throw new SHRWebException("获取员工部门信息失败!", e);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            throw new SHRWebException("获取员工部门信息失败!", e);
        }
        JSONUtils.SUCCESS(map);
    }

    public void canSubmitEffectAction(HttpServletRequest request, HttpServletResponse response,
            ModelMap modelMap) throws SHRWebException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("state", "success");
        JSONUtils.writeJson(response, map);
    }

    /**
     * 
     * <p>
     * Title: submitEffectAction
     * </p>
     * <p>
     * Description: 提交生效
     * </p>
     * 
     * @author 程赛赛
     * @param req
     * @param res
     * @param modelMap
     * @throws SHRWebException
     */
    public void submitEffectAction(HttpServletRequest req, HttpServletResponse res, ModelMap modelMap)
            throws SHRWebException {

        CoreBaseInfo model = (CoreBaseInfo) req.getAttribute("dynamic_model");
        try {
            IBusCostCount iBusCostCount = BusCostCountFactory.getRemoteInstance();
            IObjectPK objectPK = iBusCostCount.submitEffect(model);
            model.setId(BOSUuid.read(objectPK.toString()));
        } catch (EASBizException e) {
            throw new SHRWebException(e.getMessage());
        } catch (Exception e) {
            throw new ShrWebBizException(e.getMessage());
        }

        System.out.println("班车费变动情况核算表id：" + model.getId().toString());

        writeSuccessData(model.getId().toString());
    }

    /**
     * 
     * <p>
     * Title: joinSql
     * </p>
     * <p>
     * Description: 拼接sql，根据人员姓名带出部门拼接sql，根据人员姓名带出部门
     * </p>
     * 
     * @author 程赛赛
     * @param personId 人员内码
     * @return
     */
    public String joinSql(String personId) {

        sql.append("SELECT org.fid as id ,org.fname_l2 as name FROM T_ORG_POSITIONMEMBER personStion").append(
                " left join T_ORG_Position pos on personStion.FPOSITIONID=pos.fid left join T_ORG_ADMIN org on pos.FADMINORGUNITID =org.fid")
                .append(" where personStion.FISPRIMARY =1 and personStion.fpersonid=")
                .append("'" + personId + "'");

        System.out.println("============根据人员姓名带出部门的sql:" + sql.toString() + "===========");

        return sql.toString();

    }

    /**
     * <p>
     * Title: afterCreateNewModel
     * </p>
     * <p>
     * Description: 带出当前日期
     * </p>
     */
    protected void afterCreateNewModel(HttpServletRequest request, HttpServletResponse response,
            CoreBaseInfo coreBaseInfo) throws SHRWebException {
        super.afterCreateNewModel(request, response, coreBaseInfo);

        Date nowDate = DateTimeUtils.truncateDate(new Date());
        UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(this.ctx);
        BusCostCountInfo info = (BusCostCountInfo) coreBaseInfo;
        info.setCreator(currentUserInfo);
        info.setBizDate(nowDate);
    }

    @Override
    protected void beforeSave(HttpServletRequest request, HttpServletResponse response, CoreBaseInfo model)
            throws SHRWebException {
        super.beforeSave(request, response, model);
        BusCostCountInfo bill = (BusCostCountInfo) model;
        bill.setBillState(HRBillStateEnum.SAVED);
    }

    @Override
    protected void beforeSubmit(HttpServletRequest request, HttpServletResponse response, CoreBaseInfo model)
            throws SHRWebException {
        super.beforeSubmit(request, response, model);

        BusCostCountInfo bill = (BusCostCountInfo) model;

        String userID = HRFilterUtils.getCurrentUserId(ctx);
        String functionName = "com.kingdee.eas.custom.buscostcount.app.BusCostCountEditUIFunction";
        String operationName = "actionSubmit";
        try {
            String temp = EnactmentServiceProxy.getEnacementService(ctx).findSubmitProcDef(userID, bill,
                    functionName, operationName);
            if ((temp == null) || (temp.trim().equals("")))
                throw new ShrWebBizException("没有可用的班车补助单工作流");
        } catch (WfException e) {
            throw new SHRWebException(e.getMessage());
        } catch (BOSException e) {
            throw new SHRWebException(e.getMessage());
        }

        bill.setBillState(HRBillStateEnum.SUBMITED);
        String operateStatus = request.getParameter("operateState");
        if ((StringUtils.isEmpty(operateStatus)) || (!("ADDNEW".equalsIgnoreCase(operateStatus)))) {
            return;
        }
        bill.setExtendedProperty("isAddNew", "isAddNew");
    }

}
